 
using System.Collections.Generic;
using System.Reflection;
 
using System.Linq;
using CarTrackr.Business.Validation;


namespace CarTrackr.Business
{
    
    public  abstract class BusinessBase
    {

        public Dictionary<string,Rule> BrokenRules
        {
            get; private set;
        }

        public Dictionary<string, Rule> Rules
        {
            get; set;

        }

        public bool IsValid
        {
           get
           {
               foreach (Rule rule in Rules.Values)
               {
                   ValidateRule(rule);
               }

               return (BrokenRules.Count == 0);
           }
        }


        public BusinessBase()
        {
            BrokenRules = new Dictionary<string,Rule> ();

            Rules = new Dictionary<string, Rule>();

        }

        public void AddRule(Rule rule)
        {
            Rules[rule.RuleKey] = rule;
        }

      
        public void AddBrokenRule(Rule rule)
        {
            BrokenRules[rule.RuleKey] = rule;
            
        }

    
        public void RemoveBrokenRule(Rule rule)
        {

            if (BrokenRules.Keys.Contains(rule.RuleKey))
            {
                BrokenRules.Remove(rule.RuleKey);
            }
      
        }

     
           
     

        public void ValidateRule(Rule  rule)
        {
         
                PropertyInfo property = GetType().GetProperty(rule.PropertyName,
                                                              BindingFlags.Public | BindingFlags.Instance);

                var value = property.GetValue(this, null);

                string valueString = value == null ? "" : value.ToString();

                
               if (rule.Validate(valueString))
               {

                   RemoveBrokenRule(rule);

                   return;
               }

               AddBrokenRule(rule);            

        }

  
    }
}

 
          
 
      

     
